<template>
  <div class="details">
    <div
      v-if="isLoading"
      v-loading="isLoading"
      element-loading-text="Loading..."
      class="loading"
    ></div>
    <template v-else-if="loadError">
      <el-result icon="error" title="未找到指定页面" sub-title="请返回审核列表">
        <template #extra>
          <el-button type="primary" @click="handleBack">返回</el-button>
          <el-button v-if="route.query?.auditId" @click="handleLoad">
            重新加载
          </el-button>
        </template>
      </el-result>
    </template>
    <template v-else>
      <layoutPage>
        <template #search>
          <div class="top">
            <el-descriptions class="basic-info" :column="4">
              <template #title>
                <div class="title">
                  <el-tag :type="status.colorType" size="small" effect="dark">
                    {{ status.label }}
                  </el-tag>
                  <span>【{{ basicInfo.businessId }}】</span>
                  <span>{{ businessType }}</span>
                </div>
              </template>
              <el-descriptions-item label="提交部门：">
                {{ basicInfo.deptName }}
              </el-descriptions-item>
              <el-descriptions-item label="提交人：">
                {{ basicInfo.creatorName }}
              </el-descriptions-item>
              <el-descriptions-item label="提交时间：">
                {{ updateTime(basicInfo.createTime, 'YYYY-MM-DD HH:mm:ss') }}
              </el-descriptions-item>
              <el-descriptions-item label="关联信息：">
                {{ basicInfo.businessInfo }}
              </el-descriptions-item>
            </el-descriptions>
            <div class="buttonList">
              <!-- <el-button
                v-if="canWithdraw"
                type="primary"
                @click="handleWithdraw"
              >
                撤回申请
              </el-button> -->
              <el-button v-if="canApply" type="success" @click="handleApply">
                审核通过
              </el-button>
              <el-button v-if="canReject" type="danger" @click="handleRejected">
                审核驳回
              </el-button>
            </div>
          </div>
        </template>
        <template #default>
          <component
            :is="loadComponents[basicInfo.businessType]"
            :component-data="{ type: 'audit', id: basicInfo.businessId }"
          />
        </template>
      </layoutPage>
    </template>
  </div>
  <!--通用-->
  <el-dialog
    v-model="versatileVisible"
    :title="versatileTitle"
    width="500"
    destroy-on-close
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleVersatileClose"
  >
    <el-form
      ref="versatileFormRef"
      :model="versatileForm"
      :rules="versatileRules"
      status-icon
      label-position="top"
    >
      <el-form-item label="说明" prop="explanation">
        <el-input
          v-model="versatileForm.explanation"
          type="textarea"
          :rows="5"
          placeholder="请输入"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="versatileVisible = false">取消</el-button>
      <el-button type="primary" @click="handleVersatileSumbit">确定</el-button>
    </template>
  </el-dialog>
  <!--特定-->
  <el-dialog
    v-model="approvedVisible"
    title="审核通过"
    width="500"
    destroy-on-close
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleApprovedClose"
  >
    <el-form
      ref="approvedFormRef"
      :model="approvedForm"
      :rules="approvedRules"
      status-icon
      label-position="top"
    >
      <el-form-item label="说明" prop="explain">
        <el-input
          v-model="approvedForm.explain"
          type="textarea"
          :rows="5"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="项目主管部门审批意见" prop="plain">
        <el-input
          v-model="approvedForm.plain"
          type="textarea"
          :rows="8"
          placeholder="请输入"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="approvedVisible = false">取消</el-button>
      <el-button type="primary" @click="handleApprovedSumbit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import type { FormInstance, FormRules } from 'element-plus'
  import layoutPage from '@/components/layoutPage.vue'
  import { useTimeFormat } from '@/utils/useTimeFormat'
  import {
    detailsInfoProps,
    versatileDialogProps,
    approvedDialogProps,
    resDetailsProps,
    resAuditProps,
  } from '../interface'
  import {
    getAuditProcessGetDetails,
    postAuditProcessProcessNode,
  } from '@/api/project/audit'
  import { useDictStore } from '@/store/modules/dict'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const { closeTabNavigate } = useCloseTabNavigate()

  const _discStore = useDictStore()

  const { updateTime } = useTimeFormat()

  const route = useRoute()

  // 加载状态
  const isLoading = ref<boolean>(false)
  const componentLoaded = ref<boolean>(false)
  const loadError = ref<boolean>(false)

  // 加载的组件
  const loadComponents = {
    PROBLEM_INITIATION: defineAsyncComponent(
      () => import('@/views/researchProblems/details/index.vue')
    ),
    YEAR_BUDGET: defineAsyncComponent(
      () => import('@/views/researchFunds/annualBudget/details/index.vue')
    ),
    FIELD_EXPERIMENT_FUNDING: defineAsyncComponent(
      () => import('@/views/researchFunds/fieldTest/details/index.vue')
    ),
    PROJECT_INITIATION: defineAsyncComponent(
      () => import('@/views/project/approval/suggest/detail.vue')
    ),
    FUNDING_JOBS: defineAsyncComponent(
      () => import('@/views/researchFunds/work/details/index.vue')
    ),
    FUNDING_APPROPRIATION: defineAsyncComponent(
      () => import('@/views/researchFunds/allocationForm/details/index.vue')
    ),
    FUNDING_NEXT_YEAR: defineAsyncComponent(
      () => import('@/views/researchFunds/useApplication/details/index.vue')
    ),
    FUNDING_ADJUST: defineAsyncComponent(
      () => import('@/views/researchFunds/adjApplication/details/index.vue')
    ),
    TOPIC_OPENING_INITIATION: defineAsyncComponent(
      () => import('@/views/project/approval/report/detail.vue')
    ),
    PROJECT_PLAN: defineAsyncComponent(
      () => import('@/views/project/approval/plan/detail.vue')
    ),
    PROJECT_PLAN_TASK: defineAsyncComponent(
      () => import('@/views/project/approval/task/detail.vue')
    ),
    PROJECT_CHANGE: defineAsyncComponent(
      () => import('@/views/project/course/alter/detail.vue')
    ),
    PROJECT_ACCEPT: defineAsyncComponent(
      () => import('@/views/project/accept/task-in/detail.vue')
    ),
  }

  // 返回
  const handleBack = () => {
    closeTabNavigate({ name: 'ReviewApplicationIndex' })
  }
  // 重新加载
  const handleLoad = () => {
    if (route.query?.auditId) {
      handleSearchDetails(route.query.auditId as string)
    }
  }
  // 基本信息
  const basicInfo = reactive<Partial<detailsInfoProps>>({})

  // 状态属性
  const status: any = computed(
    () =>
      _discStore.getDictForValue('audit_status', basicInfo.auditStatus) || {
        colorType: 'info',
        label: '未知状态',
      }
  )

  // 业务类型
  const businessType = computed(
    () =>
      _discStore.getDictLabelForValue(
        'audit_business_type',
        basicInfo.businessType
      ) || '未知'
  )

  // 定义一个类型用于显示  审核 等信息
  //  1、我发起的 2、待我审核的 3、有我审核的 空是其他
  const canWithdraw = computed(() => {
    return (
      basicInfo.auditRole?.some((role) =>
        ['1', '3'].includes(role.toString())
      ) ?? false
    )
  })

  const canApply = computed(() => {
    return (
      (basicInfo.pendingNodeId &&
        basicInfo.auditRole?.some((role) =>
          ['2', '3'].includes(role.toString())
        )) ??
      false
    )
  })

  const canReject = computed(() => {
    return (
      (basicInfo.pendingNodeId &&
        basicInfo.auditRole?.some((role) =>
          ['2', '3'].includes(role.toString())
        )) ??
      false
    )
  })

  const handleSearchDetails = async (id: string) => {
    isLoading.value = true
    loadError.value = false
    try {
      const res: resDetailsProps = await getAuditProcessGetDetails({
        id,
      })
      if (res && res.data) {
        Object.assign(basicInfo, res.data)

        // 检查组件是否能加载成功
        if (loadComponents[basicInfo.businessType]) {
          componentLoaded.value = true
        } else {
          componentLoaded.value = false
          loadError.value = true
        }
      } else {
        Object.assign(basicInfo, {})
        componentLoaded.value = false
        loadError.value = true
      }
    } catch (e) {
      console.error('查询审核明细异常', e)
      Object.assign(basicInfo, {})
      componentLoaded.value = false
      loadError.value = true
    } finally {
      isLoading.value = false
    }
  }

  watch(
    () => route.query?.auditId,
    (newId: string) => {
      if (newId) {
        handleSearchDetails(newId)
      } else {
        // 当 newId 为空时，设置 loadError 为 true
        loadError.value = true
      }
    },
    { immediate: true }
  )

  // 通用的对话框
  const versatileVisible = ref<boolean>(false)
  const versatileTitle = ref<string>('')
  const versatileType = ref<string>('')

  const versatileFormRef = ref<FormInstance>()
  const versatileForm = reactive<versatileDialogProps>({
    explanation: '',
  })

  const versatileRules = reactive<FormRules<versatileDialogProps>>({
    explanation: [
      {
        required: true,
        message: '请输入说明',
        trigger: 'blur',
      },
    ],
  })

  // 点击关闭处理
  const handleVersatileClose = () => {
    versatileVisible.value = false
  }

  // 确定
  const handleVersatileSumbit = async () => {
    const valid = await versatileFormRef.value.validate()
    if (valid) {
      console.log('审核提交数据:')
      try {
        let isApprove = false
        if (versatileType.value === 'apply') isApprove = true
        const params = {
          // rejected
          nodeId: basicInfo.pendingNodeId,
          approve: isApprove,
          explanation: versatileForm.explanation,
        }
        const res: resAuditProps = await postAuditProcessProcessNode(params)
        if (res && res.code === 0) {
          if (isApprove) ElMessage.success('审核成功')
          else ElMessage.success('驳回成功')
          handleVersatileClose()
          closeTabNavigate()
        } else {
          if (isApprove) ElMessage.error(`审核失败: ${res.msg || '未知错误'}`)
          else ElMessage.error(`驳回失败: ${res.msg || '未知错误'}`)
        }
      } catch (e) {
        console.error('审核失败', e)
      }
    } else {
      console.error('审核失败')
    }
  }

  // --特定-- 最后一个审核环节 判断审核人是否为最后一个审核环节如果是 显示这个对话框
  // 是否最后的审核人
  const finalApprover = ref<boolean>(false)
  const approvedVisible = ref<boolean>(false)

  const approvedFormRef = ref<FormInstance>()
  const approvedForm = reactive<approvedDialogProps>({
    explain: '',
    plain: '',
  })

  const approvedRules = reactive<FormRules<approvedDialogProps>>({
    explain: [
      {
        required: true,
        message: '请输入说明',
        trigger: 'blur',
      },
    ],
    plain: [
      {
        required: true,
        message: '请输入说明',
        trigger: 'blur',
      },
    ],
  })

  // 点击关闭处理
  const handleApprovedClose = () => {
    approvedVisible.value = false
  }

  // 确定
  const handleApprovedSumbit = () => {
    console.log('handleApprovedSumbit')
    approvedFormRef.value.validate((isValidate) => {
      if (isValidate) {
        console.log('success')
      } else {
        console.log('failt')
      }
    })
  }

  // 撤回申请处理
  const handleWithdraw = () => {
    versatileTitle.value = '撤回申请'
    versatileType.value = 'withdraw'
    versatileVisible.value = true
  }

  // 审核通过
  const handleApply = () => {
    if (!finalApprover.value) {
      versatileTitle.value = '审核通过'
      versatileType.value = 'apply'
      versatileVisible.value = true
    } else {
      approvedVisible.value = true
    }
  }

  // 审核驳回
  const handleRejected = () => {
    versatileTitle.value = '审核驳回'
    versatileType.value = 'rejected'
    versatileVisible.value = true
  }
</script>

<style lang="scss" scoped>
  .details {
    .loading {
      height: 50vh;
    }
    :deep(.el-tabs__content) {
      overflow: inherit;
    }
    :deep(.el-tabs__header) {
      margin: 0 0 20px;
    }

    .top {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
      :deep(.basic-info) {
        flex-grow: 1;
        margin-right: 20px;
        border-right: 1px solid #edeff2;
        .title {
          display: inline-flex;
          align-items: center;
          font-size: 18px;
        }
        .el-descriptions__label {
          margin-right: 0px !important;
        }
        .el-descriptions__title {
          padding-left: 0px;
          border: none;
        }
      }
    }
    .buttonList {
      display: flex;
      flex-direction: column;
      align-items: stretch;
      .el-button {
        flex: 1; /* 使按钮在垂直方向上占据相同的空间 */
        width: 100%; /* 使按钮在水平方向上占据父容器的宽度 */
        + .el-button {
          margin-top: 10px;
          margin-left: 0px;
        }
      }
    }
  }
</style>
